<?php

namespace App\Livewire;

use App\Models\Video;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class VideoList extends Component
{
    use WithPagination;

    public int $perPage = 4;

    public int $page = 1;

    public Collection $collection;

    public bool $hasMorePages;

    #[Url]
    public string $cid = '';

    #[Url]
    public string $sortBy = '';

    #[Url]
    public string $abbr = '';

    #[Url]
    public string $tag = '';

    #[Url]
    public string $vip = '';

    #[Url]
    public string $search = '';

    public int $total = 0;

    public function mount(): void
    {
        $this->collection = Collection::make();

        $this->loadMore();
    }

    public function loadMore(): void
    {
        $collection = Video::query()
            ->when($this->cid, function (Builder $query, $value) {
                $query->whereRelation('categories', 'id', $value);
            })
            ->when($this->abbr, function (Builder $query, $value) {
                $query->where('abbr', 'like', $value.'%');
            })
            ->when($this->tag, function (Builder $query, $value) {
                $query->whereRelation('tags', 'id', $value);
            })
            ->when($this->vip, function (Builder $query, $value) {
                $query->where('vip', (bool) $value);
            })
            ->when($this->search, function (Builder $query, $value) {
                $query->whereFullText('title', $value);
            })
            ->latest($this->getSortBy())
            ->paginate(perPage: 10, page: $this->page);

        $this->total = $collection->total();
        $this->collection->push(...$collection->items());

        if ($this->hasMorePages = $collection->hasMorePages()) {
            $this->page++;
        }
    }

    protected function getSortBy(): ?string
    {
        return match ($this->sortBy) {
            'score' => 'score',
            'hot' => 'visits',
            'like' => 'like',
            'play' => 'playback',
            'vip' => 'vip',
            default => null,
        };
    }

    public function render()
    {
        return view('livewire.video-list');
    }
}
